<template>
  <div class="main_box" style="padding:10px">
    <div class="add_wrap">
      <div class="tit">
        <h2>基础信息</h2>
        <el-button
          type="success"
          plain
          size="small"
          icon="fa fa-mail-forward"
          @click="returnList"
          >返回</el-button
        >
      </div>
      <el-form
        :model="addForm"
        ref="addForm"
        label-width="200px"
        :rules="isAdd ? roleRules : roleRules2"
        :validate-on-rule-change="false"
      >
        <el-row>
          <el-form-item label="登录名：" prop="loginName">
            <el-input
              v-model="addForm.loginName"
              @keydown.native="keydown($event)"
              :clearable="true"
            ></el-input>
          </el-form-item>
          <el-form-item label="登录密码：" prop="password" v-if="isAdd">
            <el-input
              v-model="addForm.password"
              @keydown.native="keydown($event)"
              :clearable="true"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户名：" prop="adminName">
            <el-input
              v-model="addForm.adminName"
              @keydown.native="keydown($event)"
              :clearable="true"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号：" prop="phone">
            <el-input
              v-model="addForm.phone"
              @keydown.native="keydown($event)"
              :clearable="true"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户角色：" prop="adminRole" >
            <el-select
              :disabled="addForm.adminId?true:false"
              v-model="addForm.adminRole"
              placeholder="请选择用户角色"
              @change="adminRoleChange"
            >
              <el-option label="系统用户" :value="1"></el-option>
              <el-option label="医生用户" :value="2"></el-option>
              <el-option label="医检用户" :value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属部门：" prop="departId">
            <el-select v-model="addForm.departId" placeholder="请选择所属部门">
              <el-option
                v-for="item in departList"
                :key="item.departId"
                :label="item.departName"
                :value="item.departId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="详细地址：" prop="liveAddress">
            <el-input
              v-model="addForm.liveAddress"
              :clearable="true"
            ></el-input>
          </el-form-item>
          <el-form-item label="是否语音提醒" prop="isRemind">
            <el-radio-group v-model="addForm.isRemind">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注：" prop="remark">
            <el-input v-model="addForm.remark" :clearable="true"></el-input>
          </el-form-item>
        </el-row>

        <div
          class="tit"
          v-if="this.institutionType == 1 || this.institutionType == 2"
        >
          <h2>关联信息</h2>
        </div>
        <el-row v-if="this.institutionType == 1 || this.institutionType == 2">
          <el-form-item
            label="医检名称"
            prop="institutionId"
            v-if="this.institutionType == 2"
          >
            <el-select
              v-model="addForm.institutionId"
              filterable
              clearable
              reserve-keyword
              :loading="loadingIns"
              placeholder="请选择医检机构"
              @change="institutionChange"
            >
              <el-option
                v-for="item in pickInstitutionList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="医院名称"
            prop="hospitalId"
            v-if="this.institutionType == 1"
          >
            <el-select
              v-model="addForm.hospitalId"
              filterable
              clearable
              reserve-keyword
              :loading="loadingIns"
              placeholder="请选择医院"
              @change="hospitalChange"
            >
              <el-option
                v-for="item in pickHospitalList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="科室名称" prop="officeId">
            <el-select
              v-model="addForm.officeId"
              clearable
              filterable
              reserve-keyword
              :loading="loadingIns"
              placeholder="请选择科室"
              @change="officeChange"
            >
              <el-option
                v-for="item in pickOfficeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="医生名称" prop="doctorId">
            <el-select
              v-model="addForm.doctorId"
              filterable
              clearable
              reserve-keyword
              :loading="loadingIns"
              placeholder="请选择医生"
            >
              <el-option
                v-for="item in pickDoctorList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item>
            <el-button plain type="primary" @click="sureAddClick"
              >保 存</el-button
            >
            <el-button @click="returnList">取 消</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import AuthApi from "@/api/system/auth";
import * as message from "@/constants/message";
import ProvinceCity from "@/components/ProvinceCity";
import InstitutionApi from "@/api/institution/institution";
import HospitalApi from "@/api/institution/hospital";
import OfficeApi from "@/api/institution/office";
import DoctorApi from "@/api/institution/doctor";
import DepartApi from "@/api/system/depart";

export default {
  data() {
    return {
      addForm: {
        adminId: "",
        imageUrl: "",
        loginName: "",
        password: "",
        adminName: "",
        phone: "",
        departId: "",
        remark: "",
        isRemind: 1,
        institutionId: "",
        hospitalId: "",
        officeId: "",
        doctorId: "",
        doctorIds: [],
        adminType: 1,
        adminRole: "",
        liveAddress: ""
      },
      institutionType: "",
      loadingIns: false,
      pickInstitutionList: [],
      pickHospitalList: [],
      pickOfficeList: [],
      pickDoctorList: [],
      departList: [],
      isAdd: true,
      roleRules: {
        loginName: [
          { required: true, message: "请输入登录名", trigger: "blur" },
          { max: 15, message: "长度不超过15个字", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        adminName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { max: 15, message: "长度不超过15个字", trigger: "blur" }
        ],
        adminRole: [{ required: true, message: "请选择角色类型", trigger: "change" }],
        isRemind: [
          { required: true, message: "请选择是否语音提醒", trigger: "change" }
        ],
        departId: [
          { required: true, message: "请选择所属部门", trigger: "change" }
        ]
      },
      roleRules2: {
        loginName: [
          { required: true, message: "请输入登录名", trigger: "blur" },
          { max: 15, message: "长度不超过15个字", trigger: "blur" }
        ],
        adminName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { max: 15, message: "长度不超过15个字", trigger: "blur" }
        ],
        isRemind: [
          { required: true, message: "请选择是否语音提醒", trigger: "change" }
        ],
        departId: [
          { required: true, message: "请选择所属部门", trigger: "change" }
        ]
      }
    };
  },
  components: {
    ProvinceCity
  },
  beforeRouteLeave(to, from, next) {
    to.meta.keepAlive = true;
    next();
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.getDepartList();
      this.listInstitution();
      this.listHospital();
      this.getData();
    },
    getData() {
      if (this.$route.query.id) {
        this.isAdd = false;
        this.addForm.adminId = this.$route.query.id;
        AuthApi.getAdminInfo({ adminId: this.$route.query.id }).then(res => {
          this.$Utils.bindingBean(this.addForm, res.data);
          if (res.data.institutionId) {
            this.addForm.institutionId = parseInt(res.data.institutionId);
            this.institutionChange();
          }
          if (res.data.hospitalId) {
            this.addForm.hospitalId = parseInt(res.data.hospitalId);
            this.hospitalChange();
          }
          if (res.data.adminRole) {
            //this.addForm.adminRole = parseInt(res.data.adminRole);
            this.institutionType = parseInt(res.data.adminRole) - 1;
            if (this.institutionType === 1) {
              // 医院
              if (res.data.officeId) {
                this.addForm.officeId = parseInt(res.data.officeId);
                this.officeChange();
              }
              // 医生
              if (res.data.doctorId) {
                this.addForm.doctorId = parseInt(res.data.doctorId);
              }
            } else if (this.institutionType === 2) {
              // 科室
              if (res.data.officeId) {
                this.addForm.officeId = parseInt(res.data.officeId);
                this.officeChange();
              }
               // 医生
              if (res.data.doctorId) {
                this.addForm.doctorId = parseInt(res.data.doctorId);
              }

            }
          }

          if (res.data.isRemind) {
            this.addForm.isRemind = parseInt(res.data.isRemind);
          }
          this.addForm.departId = parseInt(res.data.departId);
        });
      }
    },
    handleItemChange(val) {
      this.addForm.residentAreaIds = [val.provinceId, val.cityId];
    },
    // 禁止输入空格
    keydown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    sureAddClick() {
      this.$refs.addForm.validate(valid => {
        if(this.addForm.adminRole==2&&!this.addForm.hospitalId){
           this.$message.error("请选择医院");
             return;
        }
        if(this.addForm.adminRole==3&&!this.addForm.institutionId){
           this.$message.error("请选择医检机构");
             return;
        }
        // 判断手机号
        if(!this.$Utils.isMobile(this.addForm.phone)&&this.addForm.phone.length>0){
               this.$message.error("手机号码格式错误");
             return;
        }
        //
        if (valid) {
          this.$confirm(
            message.MSG_CONFIRM_SAVE,
            message.TITLE_PROMPT,
            {}
          ).then(() => {
            if (this.addForm.adminId) {
              this.editData();
            } else {
              this.addData();
            }
          });
        }
      });
    },
    addData() {
      let data = {
        imageUrl: this.addForm.imageUrl,
        loginName: this.addForm.loginName,
        password: this.addForm.password,
        adminName: this.addForm.adminName,
        institutionId: this.addForm.institutionId,
        hospitalId: this.addForm.hospitalId,
        officeId: this.addForm.officeId,
        doctorId: this.addForm.doctorId,
        phone: this.addForm.phone,
        remark: this.addForm.remark,
        departId: this.addForm.departId,
        isRemind: this.addForm.isRemind,
        adminType: this.addForm.adminType,
        adminRole: this.addForm.adminRole,
        liveAddress: this.addForm.liveAddress
      };
      AuthApi.addAdmin(data).then(data => {
        this.$Utils.notifySuccess();
        this.returnList();
      });
    },
    editData() {
      let data = {
        adminId: this.addForm.adminId,
        imageUrl: this.addForm.imageUrl,
        loginName: this.addForm.loginName,
        adminName: this.addForm.adminName,
        institutionId: this.addForm.institutionId,
        hospitalId: this.addForm.hospitalId,
        departId: this.addForm.departId,  // 修改用户部门
        officeId: this.addForm.officeId,
        doctorId: this.addForm.doctorId,
        phone: this.addForm.phone,
        remark: this.addForm.remark,
        isRemind: this.addForm.isRemind,
        adminType: this.addForm.adminType,
        adminRole: this.addForm.adminRole,
        liveAddress: this.addForm.liveAddress
      };
      AuthApi.editAdmin(data).then(data => {
        this.$Utils.notifySuccess();
        this.returnList();
      });
    },
    adminRoleChange() {
      let _this = this;
      if (_this.addForm.adminRole == 2) {
        _this.institutionType = 1;
      } else if (_this.addForm.adminRole == 3) {
        _this.institutionType = 2;
      } else {
        _this.institutionType = "";
      }
      _this.addForm.institutionId = "",
      _this.addForm.hospitalId = "",
      _this.pickOfficeList = [];
      _this.addForm.officeId = "";
      _this.pickDoctorList = [];
      _this.addForm.doctorId = "";
    },
    listInstitution() {
      let _this = this;
      _this.loadingIns = true;
      let cond = {
        institutionType: 1
      };
      InstitutionApi.getInstitutionNameList(cond)
        .then(res => {
          setTimeout(() => {
            _this.loadingIns = false;
            _this.pickInstitutionList = res.data.map(item => {
              return {
                value: item.institutionId,
                label: item.institutionName
              };
            });
          }, 200);
        })
        .catch(error => {
          _this.pickInstitutionList = [];
          console.error(error);
        });
    },
    listHospital() {
      let _this = this;
      _this.loadingIns = true;
      let cond = {
        hospitalType: 1
      };
      HospitalApi.getHospitalNameList(cond)
        .then(res => {
          setTimeout(() => {
            _this.loadingIns = false;
            _this.pickHospitalList = res.data.map(item => {
              return {
                value: item.hospitalId,
                label: item.hospitalName
              };
            });
          }, 200);
        })
        .catch(error => {
          _this.pickHospitalList = [];
          console.error(error);
        });
    },
    institutionChange() {
      let _this = this;
      _this.pickOfficeList = [];
      _this.addForm.officeId = "";
      _this.pickDoctorList = [];
      _this.addForm.doctorId = "";
      if (
        _this.addForm.institutionId == "" ||
        _this.addForm.institutionId == null
      ) {
        _this.$message.error("请选择医检机构");
        return;
      }
      _this.pickOfficeList = [];
      _this.addForm.officeId = "";
      _this.pickDoctorList = [];
      _this.addForm.doctorId = "";
      let cond = {
        institutionId: _this.addForm.institutionId
      };
      OfficeApi.getOfficeNames(cond)
        .then(res => {
          setTimeout(() => {
            _this.pickOfficeList = res.data.map(item => {
              return {
                value: item.officeId,
                label: item.officeName
              };
            });
          }, 200);
        })
        .catch(error => {
          _this.pickOfficeList = [];
          console.error(error);
        });
    },
    hospitalChange() {
      let _this = this;
       _this.pickOfficeList = [];
      _this.addForm.officeId = "";
      _this.pickDoctorList = [];
      _this.addForm.doctorId = "";
      if (_this.addForm.hospitalId == "" || _this.addForm.hospitalId == null) {
        _this.$message.error("请先选择医院");
        return;
      }
      let cond = {
        hospitalId: _this.addForm.hospitalId
      };
      OfficeApi.getOfficeNames(cond)
        .then(res => {
          setTimeout(() => {
            _this.pickOfficeList = res.data.map(item => {
              return {
                value: item.officeId,
                label: item.officeName
              };
            });
          }, 200);
        })
        .catch(error => {
          _this.pickOfficeList = [];
          console.error(error);
        });
    },
    officeChange() {
      let _this = this;
      _this.addForm.doctorId = "";
      _this.pickDoctorList = []
      if (_this.addForm.officeId == "" || _this.addForm.officeId == null) {
        _this.$message.error("请先选择科室");
        return;
      }
      let cond = {
        officeId: _this.addForm.officeId
      };
      DoctorApi.getDoctorNames(cond)
        .then(res => {
          setTimeout(() => {
            _this.pickDoctorList = res.data.map(item => {
              return {
                value: item.doctorId,
                label: item.doctorName
              };
            });
          }, 200);
        })
        .catch(error => {
          _this.pickDoctorList = [];
          console.error(error);
        });
    },
    getDepartList() {
      DepartApi.listDepart({}).then(res => {
        this.departList = res.data;
      });
    },
    returnList() {
      this.$store.dispatch("delView", this.$route);
      this.$router.push({ path: "/sys/userManagement" });
    }
  }
};
</script>
<style lang="scss" src="@/assets/css/views/add.scss" scope></style>
